package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    /**
     * 自媒体文章审核
     * @param id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id){
        // 1. 查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        if(wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            
            // 获取图片和文本内容
            Map<String, Object> textAndImages = handleTextAndImages(wmNews);

            // 自管理敏感词
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("content"), wmNews);
            if(!isSensitive) return;

            // 2. 文章文本审核
            boolean isTextScan = handleTextScan((String) textAndImages.get("content"), wmNews);
            if(!isTextScan) return;
            // 3. 文章图片审核
            boolean isImageScan = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
            if(!isImageScan) return;
            // 4. 审核通过, 保存app端相关文章
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文字审核, 保存app端相关文章数据失败");
            }
            // 回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, 9, "审核成功");
        }
    }

    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        // 查询敏感词
        List<WmSensitive> wmSensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        // 初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);
        // 查看文章中是否包含敏感词
        Map<String, Integer> wordMap = SensitiveWordUtil.matchWords(content);
        if(wordMap.size() > 0){
            updateWmNews(wmNews, 2, "当前文章中存在违规内容:" + wordMap);
            flag = false;
        }
        return flag;
    }

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    public ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        // 文章的布局
        dto.setLayout(wmNews.getType());
        // 频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }
        // 作者
        dto.setAuthorId(Long.valueOf(wmNews.getUserId()));
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmNews != null){
            dto.setAuthorName(wmUser.getName());
        }
        // 设置文字id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;

        if(images == null || images.size() == 0){
            return flag;
        }

        List<byte[]> list = new ArrayList<>();
        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        try{
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                // 从byte[]转换为BufferedImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                // 识别图片文字
                String result = tess4jClient.doOCR(imageFile);
                System.out.println("识别内容: " + result);
                // 审核是否包含敏感词
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }

                list.add(bytes);
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        try {
            // Map map = greenImageScan.imageScan(list);
            Map map = new HashMap<>();
            map.put("suggestion", "passed");
            if(map != null){
                // 违规内容
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews, 2, "当前文章中存在违规内容");
                }
                // 不确定内容, 需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews, 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            throw new RuntimeException(e);
        }
        return flag;
    }

    /**
     * 审核纯文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        content += wmNews.getTitle();
        if(StringUtils.isEmpty(content)){
            return flag;
        }
        try {
            // Map map = greenTextScan.greeTextScan(content);
            Map map = new HashMap<>();
            map.put("suggestion", "passed");
            if(map != null){
                // 违规内容
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews, 2, "当前文章中存在违规内容");
                }
                // 不确定内容, 需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews, 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, int status, String reason) {
        wmNews.setStatus((short) status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 获取图片和文本内容
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 图片路径
        List<String> imgList = new ArrayList<>();
        // 文本内容
        StringBuilder builder = new StringBuilder();

        // 从自媒体文章的内容中提取文章和图片
        if(StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("image")) {
                    imgList.add((String) map.get("value"));
                } else if (map.get("type").equals("text")) {
                    builder.append(map.get("value"));
                }
            }
        }
        // 提取文章的封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            imgList.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", builder.toString());
        resultMap.put("images", imgList);
        return resultMap;
    }
}
